import Vue from 'vue'
import VueRouter from 'vue-router'

import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'

import store from '@/store'

// 路由懒加载
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list.vue')
const ProDetail = () => import('@/views/prodetail')
const Pay = () => import('@/views/pay')
const MyOrder = () => import('@/views/myorder')
Vue.use(VueRouter)

const routes = [
  { path: '/', 
  component: Layout,
  redirect: '/home',
    children: [
      { path: '/home', component: Home },
      { path: '/category', component: Category },
      { path: '/cart', component: Cart },
      { path: '/user', component: User },
    ]
  },
  { path: '/login', component: Login },
  { path: '/category', component: Search },
  { path: '/search', component: Search },
  { path: '/searchlist', component: SearchList },
  // 动态路由传参，确认将来是哪个商品，路由参数中携带 Id
  { path: '/prodetail/:id', component: ProDetail },
  { path: '/pay', component: Pay },
  { path: '/myorder', component: MyOrder },

]

const router = new VueRouter({
  routes
})

// 所有路由在真正被访问（渲染）之前，都会先经过全局前置路由守卫
// 全局前置导航守卫
// 1. to  往哪里去， 到哪去的路由信息对象
// 2. from 从哪里来， 从哪来的路由信息对象
// 3. next() 是否放行
//   (1) 如果next()调用，就是放行
//   (2) next(路径) 拦截到某个路径页面

// 定义一个数组， 专门存放需要用户权限的页面
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // 看to.path 是否在autoUrls 中出现过
  const token = store.getters.token
  if (!authUrls.includes(to.path)) {
    // 非权限页面，直放行
    next()
    return
  }

  // 是权限页面，需要判断token
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
